﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Resource.AttachedProperty
{
    public class TextBoxEnterCommandBehavior
    {


        public static object GetEnterCommandParameter(DependencyObject obj)
        {
            return (object)obj.GetValue(EnterCommandParameterProperty);
        }

        public static void SetEnterCommandParameter(DependencyObject obj, object value)
        {
            obj.SetValue(EnterCommandParameterProperty, value);
        }

        // Using a DependencyProperty as the backing store for EnterCommandParameter.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EnterCommandParameterProperty =
            DependencyProperty.RegisterAttached("EnterCommandParameter", typeof(object), typeof(TextBoxEnterCommandBehavior), new PropertyMetadata(null));



        public static ICommand GetEnterCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(EnterCommandProperty);
        }

        public static void SetEnterCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(EnterCommandProperty, value);
        }

        // Using a DependencyProperty as the backing store for EnterCommand.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EnterCommandProperty =
            DependencyProperty.RegisterAttached("EnterCommand", typeof(ICommand), typeof(TextBoxEnterCommandBehavior), new PropertyMetadata(null, InitCommand));

        private static void InitCommand(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = d as TextBox;
            if (textBox == null)
            {
                return;
            }
            textBox.KeyDown -= TextBox_KeyDown;
            textBox.KeyDown += TextBox_KeyDown;

            //textBox.PreviewKeyDown -= TextBox_PreviewKeyDown;
            //textBox.PreviewKeyDown += TextBox_PreviewKeyDown;
        }

        //private static void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        (sender as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        //    }
        //}

        private static void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ICommand command = GetEnterCommand(sender as DependencyObject);
                object commandParameter = GetEnterCommandParameter(sender as DependencyObject);
                if(command.CanExecute(commandParameter))
                {
                    command.Execute(commandParameter);
                }
            }
        }


    }
}
